<template>
  <button id="btn-play-recording" @click="readyOriginal">获取文件</button>
</template>

<script>
  import {HZRecorder} from './HZRecorder'

  export default {
    name: "Audio2",
    mounted() {
      this.$nextTick(() => {
        try {
          // <!-- 检查是否能够调用麦克风 -->
          window.AudioContext = window.AudioContext || window.webkitAudioContext;
          navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
          window.URL = window.URL || window.webkitURL;

          audio_context = new AudioContext;
          console.log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
        } catch (e) {
          alert('No web audio support in this browser!');
        }

        navigator.getUserMedia({audio: true}, function (stream) {
          recorder = new HZRecorder(stream)
          console.log('初始化完成');
        }, function(e) {
          console.log('No live audio input: ' + e);
        });
      })
    },
    methods:{
      readyOriginal () {
        if (!this.isVoice) {
          // <!-- 开启录音 -->
          recorder && recorder.start();
          this.isVoice = true
        } else {
          this.isVoice = false
          // <!-- 结束录音 -->
          recorder && recorder.stop();
          setTimeout(()=> {
            // <!-- 录音上传 -->
            var mp3Blob = recorder.upload();
            var fd = new FormData();
            fd.append('audio', mp3Blob);
            this.$http({
              header: ({
                'Content-Type': 'application/x-www-form-urlencodeed'
              }),
              method: 'POST',
              url: 'url',
              data: fd,
              withCredentials: true,
            }).then((res) => {
              // 这里做登录拦截
              if (res.data.isLogin === false) {
                router.replace('/login');
              } else {
                if (res.data.status === 200) {
                  console.log('保存成功')
                } else {
                  this.returnmsg = '上传失败'
                }
              }
            })
          },1000)
        }
      },
    }
  }
</script>

<style scoped>

</style>
